#include "grouping.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 自定义 strdup 实现
#ifndef HAVE_STRDUP
static char* custom_strdup(const char* s) {
    if (!s) return NULL;
    size_t len = strlen(s) + 1;
    char* dup = malloc(len);
    if (dup) {
        memcpy(dup, s, len);
    }
    return dup;
}
#define strdup custom_strdup
#endif

// 简单的频率计数器实现（备用方案）
typedef struct {
    char* item;
    uint32_t count;
} FreqCounter;

typedef struct {
    FreqCounter* counters;
    uint32_t capacity;
    uint32_t count;
} FrequencyTable;

// 初始化频率表
FrequencyTable* freq_table_init() {
    FrequencyTable* ft = malloc(sizeof(FrequencyTable));
    if (!ft) return NULL;
    
    ft->capacity = 16;
    ft->count = 0;
    ft->counters = malloc(ft->capacity * sizeof(FreqCounter));
    if (!ft->counters) {
        free(ft);
        return NULL;
    }
    
    return ft;
}

// 在频率表中查找项
static int freq_table_find(FrequencyTable* ft, const char* item) {
    for (uint32_t i = 0; i < ft->count; i++) {
        if (strcmp(ft->counters[i].item, item) == 0) {
            return i;
        }
    }
    return -1;
}

// 扩展频率表
static bool freq_table_expand(FrequencyTable* ft) {
    uint32_t new_capacity = ft->capacity * 2;
    FreqCounter* new_counters = realloc(ft->counters, new_capacity * sizeof(FreqCounter));
    if (!new_counters) return false;
    
    ft->counters = new_counters;
    ft->capacity = new_capacity;
    return true;
}

// 插入项到频率表
void freq_table_insert(FrequencyTable* ft, const char* item) {
    int idx = freq_table_find(ft, item);
    if (idx >= 0) {
        ft->counters[idx].count++;
        return;
    }
    
    // 检查是否需要扩展
    if (ft->count >= ft->capacity) {
        if (!freq_table_expand(ft)) {
            return;
        }
    }
    
    // 添加新项
    ft->counters[ft->count].item = strdup(item);
    ft->counters[ft->count].count = 1;
    ft->count++;
}

// 查询项频率
uint32_t freq_table_query(FrequencyTable* ft, const char* item) {
    int idx = freq_table_find(ft, item);
    if (idx >= 0) {
        return ft->counters[idx].count;
    }
    return 0;
}

// 释放频率表资源
void freq_table_free(FrequencyTable* ft) {
    if (!ft) return;
    
    for (uint32_t i = 0; i < ft->count; i++) {
        free(ft->counters[i].item);
    }
    free(ft->counters);
    free(ft);
}